<template>
  <div class="users-base-wrapper">
    <!-- <div class="module-name">一般编码</div> -->
    <div class="details-layout">
      <!-- 搜索部分 -->
      <div class="search-bar">
        <el-form :inline="true" size="mini" :model="filters" label-width="100px" @submit.native.prevent>
          <el-row :span="24">
            <el-col :span="8">
              <el-form-item label="编码组中文：">
                <el-select v-model="filters.codeGroupcn" placeholder="请选择" filterable style="width: 220px" clearable>
                  <el-option v-for="item in codeGroupList" :key="item.codeGroupcn" :value="item.codeGroupcn">
                    <div style="text-align: justify">
                      <span>{{ item.codeGroupcn }}</span>
                      <span style="color: #9163d5; font-size: 13px">({{ item.count }})</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="编码名中文：">
                <el-select v-model="filters.codeNameCn" placeholder="请选择" filterable  style="width: 220px" clearable>
                  <el-option v-for="item in codingNameList" :key="item.codeNameCn" :value="item.codeNameCn">
                    <div style="text-align: justify">
                      <span>{{ item.codeNameCn }}</span>
                      <span style="color: #9163d5; font-size: 13px">({{ item.count }})</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :span="24" class="btn-row">
            <el-button type="primary" size="mini" @click="handleSearch">查询</el-button>
            <el-button type="default" size="mini" @click="handleResent">重置</el-button>
            <el-button type="primary" size="mini" @click="handleAdd" v-if="isOperate">新增</el-button>
            <el-button type="primary" size="mini" @click="handleDownloadTemplate" v-if="isOperate">下载导入模板</el-button>
            <el-upload
              action
              v-if="isOperate"
              style="margin-left: 8px"
              :http-request="handleImportGeneralEncoding"
              :file-list="fileList"
              :show-file-list="false"
            >
              <el-button type="primary" size="mini" :loading="importLoading">导入</el-button>
            </el-upload>
            <el-button type="primary" size="mini" style="margin-left: 8px" @click="handleDownLoadData">导出</el-button>
            <el-button type="primary" size="mini" @click="deleteAll" v-if="isOperate">批量删除</el-button>
            <el-button type="primary" size="mini" @click="invalidateAll" v-if="isOperate">批量失效</el-button>
          </el-row>
        </el-form>
      </div>
      <!-- 表格部分 -->
      <el-table
        :data="generalCodingList"
        stripe
        style="width: 100%"
        size="mini"
        :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择列 -->
        <el-table-column type="selection" width="55" align="center"> </el-table-column>
        <!-- 操作列 -->
        <el-table-column type="operate" label="操作" align="center" width="110">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <div v-if="isOperate">
              <i class="el-icon-edit table-icon" @click="handleEdit(scope.row)"></i>
              <i class="el-icon-document-copy table-icon" @click="handleCopy(scope.row)"></i>
              <i class="el-icon-delete table-icon" style="color: red" @click="handleDelete(scope.row)"></i>
            </div>
          </template>
        </el-table-column>
        <!-- 序号 -->
        <!-- <el-table-column type="index" label="序号" align="center" width="50"> </el-table-column> -->
        <!-- 插槽 -->
        <template v-for="(column, index) in tableColumns">
          <el-table-column
            v-if="column.visible"
            :width="column.width"
            :key="index"
            :min-width="column.minWidth"
            :label="column.name"
            :show-overflow-tooltip="true"
            align="center"
            :sortable="column.sortable"
            :sort-method="column.customSort"
          >
            <template slot-scope="scope">
              <div v-if="column.key === 'source1'">
                <span>{{ sourceType[scope.row.source] }}</span>
              </div>
              <!-- 排序插槽 -->
              <div v-else-if="column.key === 'sort'">
                <div v-if="!scope.row.sortInlineEditingVis">
                  <span class="table-column-text">{{ scope.row[column.key] }}</span>
                  <!-- <el-button @click.stop="handleEdit(scope.row, column.key)" style="cursor: pointer; " size="mini"
                           icon="el-icon-edit" circle></el-button> -->
                  <el-button
                    @click.stop="handleEditSort(scope.row)"
                    style="cursor: pointer"
                    size="mini"
                    icon="el-icon-edit"
                    circle
                  ></el-button>
                </div>
                <div v-if="scope.row.sortInlineEditingVis">
                  <el-input size="mini" style="width: 80px" v-model="scope.row.editSort"></el-input>
                  <el-button
                    size="mini"
                    icon="el-icon-check"
                    circle
                    style="margin-left: 8px"
                    @click="handleEditSortNumConfirm(scope.row)"
                  ></el-button>
                  <el-button
                    size="mini"
                    icon="el-icon-close"
                    circle
                    @click="handleEditSortNumCancel(scope.row)"
                  ></el-button>
                </div>
              </div>
              <div v-else-if="column.key === 'effectuate'">
                <span>{{ scope.row.effectuate === '0' ? '是' : '否' }}</span>
              </div>
              <span v-else>{{ scope.row[column.key] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <!-- 分页器 -->
      <el-row type="flex" justify="end" style="height: 60px" align="middle">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParams.pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="float: right"
        >
        </el-pagination>
      </el-row>
      <add-record
        :dialogVisible="dialogVisible"
        :dialogTitle="dialogTitle"
        :searchParams="searchParams"
        :editData="editData"
        @handleCancel="handleCancel"
      ></add-record>
    </div>
  </div>
</template>
<script>
import { mapActions } from 'vuex'
import { tableColumns } from './data'
import addRecord from './component/add-record.vue'
import { handleExportResponse } from '@/utils/index'

export default {
  name: 'general-coding',
  components: {
    addRecord,
  },

  data() {
    return {
      dialogVisible: false,
      dialogTitle: '',
      editData: {},
      generalCodingList: [],
      tableColumns,
      searchParams: {},
      pageParams: {
        pageSize: 10,
        pageNo: 1,
      },
      sourceType: {
        1: 'S',
        2: 'P',
        3: 'M',
      },
      filters: {
        codeGroupcn: '',
        codeNameCn: '',
      },
      total: 0,
      codeGroupList: [],
      codingNameList: [],
      fileList: [],
      importLoading: false,
      multipleSelection: [],
      isOperate: true
    }
  },
  mounted() {
    const databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    this.searchParams = {
      projectId: localStorage.getItem('sys-project-id') || '',
      ...databaseInfo,
    }

    if (databaseInfo.isLock === '1') {
      this.isOperate = false
    }

    this.getGeneralCodingList()
    this.getCodingGroupList()
    this.getCodingNameList()
  },

  methods: {
    ...mapActions('eCRFDesign', [
      'qryGeneralCodingList',
      'editCrfDesignStatus',
      'deleteGeneralCoding',
      'qryCodingGroupList',
      'qryCodingNameList',
      'exportGeneralEncodingTemplate',
      'exportGeneralEncodingData',
      'importGeneralEncodingData',
      'batchDeleteAPI',
      'batchInEffective',
      'updateSortAPI',
    ]),

    // 排序行内编辑
    handleEditSort(row) {
      this.$set(row, 'sortInlineEditingVis', true)
      this.$set(row, 'editSort', row.sort)
    },

    // 行内编辑确认
    async handleEditSortNumConfirm(row) {
      const data = {
        id: row.id,
        sort: row.editSort,
      }
      const res = await this.updateSortAPI({ data })
      if (res.code === 200) {
        await this.getGeneralCodingList()
        row.sortInlineEditingVis = false
      }
    },
    // 行内编辑取消
    handleEditSortNumCancel(row) {
      row.sortInlineEditingVis = false
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 多选删除
    async deleteAll() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请先选中需要删除的数据！')
      }
      const idList = []
      this.multipleSelection.forEach(item => {
        idList.push(item.id)
      })
      const data = {
        idList: idList,
      }
      this.$confirm('确定删除选中的条数据吗？', '操作提示', {
        type: 'warning',
      }).then(res => {
        this.batchDeleteAPI({ data }).then((res) => {
          if (res.code === 200) {
            this.getGeneralCodingList()
            this.$message.success('操作成功！')
          }
        })
      })
    },
    async invalidateAll() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请先选中需要删除的数据！')
      }
      const idList = []
      this.multipleSelection.forEach(item => {
        idList.push(item.id)
      })
      const data = {
        idList,
        effectuate: 1,
      }
      this.$confirm('确定批量失效选中的条数据吗？', '操作提示', {
        type: 'warning',
      }).then(res => {
        this.batchInEffective({ data }).then((res) => {
          if (res.code === 200) {
            this.getGeneralCodingList()
            this.$message.success('操作成功！')
          }
        })
      })
    },

    // 查询一般编码列表
    getGeneralCodingList() {
      const params = {
        ...this.searchParams,
        ...this.pageParams,
        ...this.filters,
      }
      this.qryGeneralCodingList({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          this.generalCodingList = data.records || []
          this.total = data.total || 0
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },

    // 获得编码组中文下拉列表
    getCodingGroupList() {
      const params = {
        ...this.searchParams,
      }
      this.qryCodingGroupList({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          this.codeGroupList = data
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },

    // 获得编码名中文列表
    getCodingNameList() {
      const params = {
        ...this.searchParams,
      }
      this.qryCodingNameList({ params }).then(res => {
        const { data, code, message } = res
        if (code === 200) {
          this.codingNameList = data
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },
    // 重置筛选条件
    handleResent() {
      this.filters = {
        codeGroupcn: '',
        codeNameCn: '',
      }
      this.pageParams.pageNo = 1
    },

    //
    handleWarn() {
      this.$message.warning('暂未开放，敬请期待~')
      return ''
    },

    // 刷新列表
    handleSearch() {
      this.pageParams.pageNo = 1
      this.getGeneralCodingList()
    },

    // 添加
    handleAdd() {
      this.dialogVisible = true
      this.editData = {}
      this.dialogTitle = '新建'
    },

    // 编辑
    handleEdit(record) {
      this.dialogTitle = '编辑'
      this.dialogVisible = true
      this.editData = { ...record }
    },

    // 复制添加
    handleCopy(record) {
      this.dialogTitle = '复制添加'
      this.dialogVisible = true
      this.editData = { ...record }
    },

    // 关闭弹框
    handleCancel(type) {
      this.dialogVisible = false
      if (type === 'refresh') {
        // 是刷新列表
        this.getGeneralCodingList()
        this.getCodingGroupList()
        this.getCodingNameList()
      }
    },

    // 删除
    handleDelete(row) {
      const params = {
        id: row.id,
      }
      this.$confirm('确定删除该条数据吗？', '删除提示', {
        type: 'warning',
      }).then(res => {
        this.deleteGeneralCoding({ params }).then(res => {
          if (res.code === 200) {
            this.$message({ message: '删除成功', type: 'success' })
            this.getGeneralCodingList()
          }
        })
      })
    },

    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.getGeneralCodingList()
    },
    handleCurrentChange(val) {
      this.pageParams.pageNo = val
      this.getGeneralCodingList()
    },

    // 下载导入模板
    handleDownloadTemplate() {
      this.exportGeneralEncodingTemplate().then(res => {
        const { data } = res
        handleExportResponse(data, '一般编码_导入模板')
      })
    },

    // 导出数据
    handleDownLoadData() {
      const data = {
        ...this.searchParams,
      }
      this.exportGeneralEncodingData({ data }).then(res => {
        const { data } = res
        handleExportResponse(data, '一般编码_列表')
      })
    },

    handleImportGeneralEncoding(file) {
      this.importLoading = true
      const formData = new FormData()
      formData.append('file', file.file)
      formData.append('projectId', this.searchParams.projectId)
      formData.append('databaseId', this.searchParams.databaseId)
      formData.append('databaseVersion', this.searchParams.databaseVersion)
      formData.append('environment', '0')

      this.importGeneralEncodingData({ data: formData })
        .then(res => {
          this.importLoading = false
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '导入成功' + res.message,
            })
            this.fileList.push({ name: file.file.name, url: res.data })
            this.handleSearch()
          } else {
            this.$message({
              type: 'error',
              message: '导入数据失败，请稍后重试~',
            })
          }
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
  },
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
